package util;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;


import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * @description 记录错误信息到数据库
 * @author GaoTong
 *
 */
public class Log {
	
	public static final String LOGIC_ERROR = "logic error";
	public static final String SQL_ERROR = "logic error";
	public static final String HTTP_ERROR = "http error";
	
	
	static private Connection conn = JdbcUtil.getConnection("decuries");
	private static Logger logger = Logger.getRootLogger();
	public static void error(String msg){
		logger.error(msg);
	}
	
	/**
	 * @author GaoTong
	 * @param msg: 错误信息
	 * @param t: 错误异常
	 */
//	public static void err2DB(String msg,Throwable t){
//		
//		System.out.println(msg);
//	}
	
	/**|
	 * 
	 * @param errorName 错误信息
	 * @param t 错误异常
	 * @param type 错误的类型，SQL错误、logic error、404 error
	 */
	public static void err2DB(String errorName,Throwable t,String type,HttpServletRequest req){
		try {
			//如果有异常
			String position = "unknown position";
			String info = "no info";
			String url = "unknown URL";
			String user = "unknown user";
			
			if(t != null){
				position = "";
				StackTraceElement[] errors = t.getStackTrace();
				position = t.getMessage();
				info = "";
				for(int i=0; i<errors.length; i++)
					info += errors[i].toString();
				type = "Exception:"+type;
			}
			if(req != null){
				user = (String) req.getSession().getAttribute("username");
				url = req.getRequestURL().toString();
			}
			
			String sql = "insert into gt_error(time,info,position,errorType,errorName,url,user) values(?,?,?,?,?,?,?)";
			PreparedStatement stm = conn.prepareStatement(sql);
			stm.setTimestamp(1, new Timestamp(new java.util.Date().getTime()));
			stm.setString(2, info);
			stm.setString(3, position);
			stm.setString(4, type);
			stm.setString(5, errorName);
			stm.setString(6, url);
			stm.setString(7, user);
			
			stm.execute();
			
		} catch (Exception e) {
			error(e.getStackTrace()[0].toString());
			e.printStackTrace();
		}
		System.out.println(errorName);
	}	

}
